const mongoose = require("mongoose");
const dayjs = require("dayjs");

const Schema = new mongoose.Schema({
    name: { type: String, required: true },
    thumbnail: { type: String, required: true },
    imageUrl: { type: String, required: true, select: false },
    collectionId: { type: mongoose.Schema.Types.ObjectId, ref: "Collection" },
    createdAt: { type: String, select: false },
    summary: { type: String, required: true, select: false },
    tags: [{ type: String }],
    downloads: {
        type: [
            {
                userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
                date: String
            }
        ],
        select: false
    },
    ratings: {
        type: [
            {
                userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
                score: { type: Number, min: 1, max: 5 },
                date: { type: Date, default: Date.now }
            }
        ],
        select: false
    },
    avgRating: { type: Number, default: 0 }
});

Schema.pre("save", function (next) {
    if (this.isNew) {
        this.createdAt = dayjs().format("YYYY/MM/DD HH:mm:ss");
    }
    if (this.ratings.length > 0) {
        this.avgRating =
            this.ratings.reduce((acc, rating) => acc + rating.score, 0) /
            this.ratings.length;
    }
    next();
});

module.exports = mongoose.model("Wallpaper", Schema);
